package com.toocms.sample.ui.tool.user;

import android.app.Application;

import androidx.annotation.NonNull;
import androidx.databinding.Observable;
import androidx.databinding.ObservableField;

import com.toocms.sample.data.User;
import com.toocms.sample.data.UserRepository;
import com.toocms.tab.base.BaseViewModel;
import com.toocms.tab.binding.command.BindingCommand;
import com.toocms.tab.network.ApiTool;

/**
 * Author：Zero
 * Date：2020/11/5 17:32
 */
public class UserViewModel extends BaseViewModel {

    public ObservableField<String> showText = new ObservableField<>();

    public UserViewModel(@NonNull Application application) {
        super(application);
        // 登录状态改变监听
        UserRepository.getInstance().isLogin.addOnPropertyChangedCallback(new Observable.OnPropertyChangedCallback() {
            @Override
            public void onPropertyChanged(Observable sender, int propertyId) {
                if (UserRepository.getInstance().isLogin.get()) loadUserInfo();
                else showToast("退出");
            }
        });
    }

    //  获取用户信息
    private void loadUserInfo() {
        ApiTool.post("http://xlg-api.uuudoo.com/Center/getInfo")
                .add("m_id", 6)
                .asTooCMSResponse(User.class)
                .withViewModel(this)
                .request(user -> {
                    UserRepository.getInstance().setUser(user);
                    showText.set("登录成功");
                });
    }

    // 登录
    public BindingCommand login = new BindingCommand(() -> {
        UserRepository.getInstance().setLogin(true);
        // 保存/获取账号密码
//        model.saveAccount("");
//        model.savePassword("");
//        model.getAccount();
//        model.getPassword();
//        loadUserInfo();
    });

    // 获取用户信息
    public BindingCommand getUserInfo = new BindingCommand(() -> showText.set(UserRepository.getInstance().getUser().toString()));

    // 获取用户id
    public BindingCommand getUserId = new BindingCommand(() -> showText.set("用户ID：" + UserRepository.getInstance().getUser().m_id));

    // 设置用户昵称
    public BindingCommand setUserNickname = new BindingCommand(() -> {
        UserRepository.getInstance().setUserInfo("nickname", "TooCMS");
        showText.set("用户昵称：" + UserRepository.getInstance().getUser().nickname);
    });

    // 退出登录
    public BindingCommand logout = new BindingCommand(() -> {
        UserRepository.getInstance().setLogin(false);
        UserRepository.getInstance().clearUserInfo();
    });

    // 检查登录状态
    public BindingCommand checkStatus = new BindingCommand(() -> showText.set(String.valueOf(UserRepository.getInstance().isLogin())));
}
